﻿using AiXiu.IService;
using AiXiu.Model;
using AiXiu.Service;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Web.Mvc;

namespace AiXiu.WebSite.Controllers
{
    [Authorize]
    public class PersonalController : Controller
    {
        public ActionResult Index()
        {
            // 读取用户资料
            TBUsers user = IdentityManager.ReadUser();
            return View(user);
        }

        public ActionResult PersonalEdit()
        {
            ViewBag.provinces = GetProvince();
            // 读取用户资料
            TBUsers user = IdentityManager.ReadUser();
            return View(user);
        }

        public List<Province> GetProvince()
        {
            List<Province> provinces=new List<Province>();
            //加载省市信息
            using (FileStream fileStream = new FileStream(Server.MapPath("~/App_Data/district.json"), FileMode.Open))
            {
                using (StreamReader streamReader = new StreamReader(fileStream, Encoding.Default))
                {
                    string str = streamReader.ReadToEnd();
                    District district = JsonConvert.DeserializeObject<District>(str);
                    provinces = district.Provinces;

                }
            }
            return provinces;
        }

        public string GetCity(string provinceName)
        {
            //加载省市信息
            using (FileStream fileStream = new FileStream(Server.MapPath("~/App_Data/district.json"), FileMode.Open))
            {
                using (StreamReader streamReader = new StreamReader(fileStream, Encoding.Default))
                {
                    string str = streamReader.ReadToEnd();
                    District district = JsonConvert.DeserializeObject<District>(str);
                    Province province = district.Provinces.FirstOrDefault(a => a.ProvinceName == provinceName);
                    List<City> cities = province.Citys;
                    return JsonConvert.SerializeObject(cities);
                }
            }
        }

        [HttpPost]
        public ActionResult SubmitEdit(TBUsers user)
        {
            IUserService userService = new UserService();
            OperResult<TBUsers> operResult=  userService.EditUser(user);
            if (operResult.StatusCode == StatusCode.Succeed)
            {
                //更新用户的缓存信息
                IdentityManager.SaveUser(user);
                return Json(OperResult.Succeed());
            }
            else
            {
                return Json(OperResult.Failed(operResult.Message));
            }
        }

        public ActionResult AvatarEdit()
        {
            return View();
        }

        public void ImageUpload(int length)
        {
            if (length <= 0)
            {
                Response.StatusCode = 400;
                Response.End();
                return;
            }
            // 读取编码流长度
            int rsLen = (int)Request.InputStream?.Length;
            if (rsLen <= 0)
            {
                Response.StatusCode = 400;
                Response.End();
                return;
            }
            // 尝试存储
            byte[] base64Bytes = new byte[Request.InputStream.Length];
            Request.InputStream.Seek(0, SeekOrigin.Begin);
            Request.InputStream.Read(base64Bytes, 0, base64Bytes.Length);
            string base64String = Encoding.Default.GetString(base64Bytes);
            // 判断是否完整接收
            if (base64String?.Length == length)
            {
                base64String = base64String.Substring(base64String.IndexOf("base64") + 7);
                byte[] baseByte = Convert.FromBase64String(base64String);
                // 保存到文件
                string randomString = Guid.NewGuid().ToString("N");
                string fileName = $"{Server.MapPath("~/avatar")}/{randomString}.jpg";
                string fileUrl = $"/avatar/{randomString}.jpg";
                using (MemoryStream memoryStream = new MemoryStream(baseByte))
                {
                    using (Image image = Image.FromStream(memoryStream))
                    {
                        image.Save(fileName, ImageFormat.Jpeg);
                    }
                }
                Response.Write(fileUrl);
                Response.End();
            }
            else
            {
                Response.StatusCode = 400;
                Response.End();
                return;
            }
        }

        [HttpPost]
        public ActionResult SubmitAvatarEdit(string avatar)
        {
            // 读取信息
            TBUsers user = IdentityManager.ReadUser();
            user.Avatar = avatar;
            // 更新资料
            IUserService userService = new UserService();
            OperResult<TBUsers> operResult = userService.EditAvatar(user);
            if (operResult.StatusCode == StatusCode.Succeed)
            {
                //更新用户的缓存信息
                IdentityManager.SaveUser(user);
                return Json(OperResult.Succeed());
            }
            else
            {
                return Json(OperResult.Failed(operResult.Message));
            }
        }        

        public ActionResult Friends()
        {
            return View();
        }

    }
}